package com.example.myapplication.ui.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.replace
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.android_program.data_class.movie_1_1
import com.example.android_program.data_class.movie_1_2
import com.example.myapplication.MovieDetailsActivity
import com.example.myapplication.R
import com.example.myapplication.ui.movie.Cinema_ChooseTimeSlot
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import com.youth.banner.loader.ImageLoader
import kotlinx.android.synthetic.main.fragment_home.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.Exception
import java.lang.StringBuilder
import java.lang.reflect.Field
import java.net.URLEncoder
import kotlin.concurrent.thread
import com.example.myapplication.ui.movie.SelectCinemaActivity
import com.example.myapplication.ui.movie.WellReceivedFragment
import com.example.myapplication.ui.movie.ToBeShownFragment
import com.example.myapplication.ui.movie.MovieFragment

class HomeFragment : Fragment() {

    val sever_ip = "192.168.43.8"
    val showAll_Home_Movie_1_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_Home_Movie_1.jsp"
    val showAll_Home_Movie_2_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_Home_Movie_2.jsp"
//    val showAll_Home_Movie_1_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_Home_Movie_1.jsp"
//    val showAll_Home_Movie_2_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_Home_Movie_2.jsp"
    val showAll_json_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_json.jsp"

    private lateinit var homeViewModel: HomeViewModel
    val moveinfo_1: ArrayList<movie_1_1> = ArrayList()
    val moveinfo_2: ArrayList<movie_1_2> = ArrayList()

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)

        return root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        Log.d("4123", "R.string.sever_ip = ${resources.getString(R.string.sever_ip)}---sever_ip = ${sever_ip}")
        Banner_initView();  //轮播图
        Recycler_data_1(); //横向列表数据加载函数
        Recycler_1_initView() //列表

        //跳转到热映
        test_1_1.setOnClickListener {
            Log.d("111", "click test_1_1, ${R.layout.fragment_home}")
            val fragment = MovieFragment()

            val fragmentManager = childFragmentManager
            val ft = fragmentManager?.beginTransaction()
            ft?.replace(R.id.home_fragment, fragment)
            ft?.commit()
        }

        //跳转到待映
        test_1_2.setOnClickListener {
            val fragment = MovieFragment()

            val fragmentManager = childFragmentManager
            val ft = fragmentManager?.beginTransaction()
            ft?.replace(R.id.home_fragment, fragment)
            ft?.commit()
        }

        
    }

    //--------------------------------------------------------------------------------------------------轮播图3个函数
    private fun Banner_initView() {
        val arrayImageUrl = arrayListOf<Int>(R.drawable.p111, R.drawable.p112, R.drawable.p113)
        val arrayTitle = arrayListOf<String>("第一张", "第二张", "第三张")
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR)
        banner.setImageLoader(MyLoader())
        banner.setImages(arrayImageUrl)
        banner.setBannerAnimation(Transformer.Default)
        banner.setBannerTitles(arrayTitle)
        banner.setDelayTime(3000)
        banner.isAutoPlay(true)
        banner.setIndicatorGravity(BannerConfig.NOT_INDICATOR)
        banner.setOnBannerListener {
            Log.d("=*=", "第几张" + it.dec())
            pagefuntion(it.dec())
        }
        banner.start()
    }
    private inner class MyLoader : ImageLoader() {
        override fun displayImage(context: Context, path: Any, imageView: ImageView) {
            Glide.with(context).load(path as Int).into(imageView)
        }
    }
    private fun pagefuntion(page: Int) {
        var temp = page + 2
        /*if (temp == 1) {
            val intent = Intent(this, MainActivity1::class.java)
            startActivity(intent)
        } else if (temp == 2) {
            val intent = Intent(this, MainActivity2::class.java)
            startActivity(intent)
        } else if (temp == 3) {
            val intent = Intent(this, MainActivity3::class.java)
            startActivity(intent)
        }*/
    }
    //--------------------------------------------------------------------------------------------------列表函数
    private fun Recycler_1_initView() {
        var layoutManager = LinearLayoutManager( context)
        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
        myrecyclerview.layoutManager = layoutManager
        var adapter = MovieAapter(moveinfo_1, this.requireContext())
        myrecyclerview.adapter = adapter
//        val movieSnapHelper = LinearSnapHelper()
//        movieSnapHelper.attachToRecyclerView(myrecyclerview)

        var layoutManager1 = LinearLayoutManager( context)
        layoutManager1.orientation = LinearLayoutManager.HORIZONTAL
        myrecyclerview1.layoutManager = layoutManager1
        var adapter2 = MovieAapter1(moveinfo_2, this.requireContext())
        myrecyclerview1.adapter = adapter2


    }

    fun Recycler_data_1() {
        getAllTrainInfoJson()
        getAllTrainInfoJson2()
        /*moveinfo_1.add(movie_1_1("电影1", R.drawable.p1, "1", R.drawable.p3))
        moveinfo_1.add(movie_1_1("电影2", R.drawable.p1, "2", R.drawable.p3))
        moveinfo_1.add(movie_1_1("电影3", R.drawable.p1, "3", R.drawable.p3))
        moveinfo_1.add(movie_1_1("电影4", R.drawable.p1, "4", R.drawable.p3))
        moveinfo_1.add(movie_1_1("电影5", R.drawable.p1, "5", R.drawable.p3))

        moveinfo_2.add(movie_1_2("电影11", R.drawable.p1, "12月20号", R.drawable.p4))
        moveinfo_2.add(movie_1_2("电影22", R.drawable.p1, "12月20号", R.drawable.p4))
        moveinfo_2.add(movie_1_2("电影33", R.drawable.p1, "12月20号", R.drawable.p5))
        moveinfo_2.add(movie_1_2("电影44", R.drawable.p1, "12月20号", R.drawable.p5))
        moveinfo_2.add(movie_1_2("电影55", R.drawable.p1, "12月20号", R.drawable.p5))*/
    }

    //1-----
    private class movieViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        // 获取对应的控件id       val train_num(与id同名):TextView(类型) = view.findViewById(R.id.id号)  把小布局的id号赋值到kotlin文件的变量中
        var move_Name: TextView = view.findViewById(R.id.moveName_1)
        var movie_Src: com.makeramen.roundedimageview.RoundedImageView = view.findViewById(R.id.movieSrc_1)
        var move_ScoreDate: TextView = view.findViewById(R.id.movieNameScoreDate_1)
        var move_goupiao: com.makeramen.roundedimageview.RoundedImageView = view.findViewById(R.id.goupiao_1)
    }
    //适配器
    private class MovieAapter(val moveinfo_1: List<movie_1_1>, val context: Context): RecyclerView.Adapter<movieViewHolder>() {
        //Ctrl+o
        //创建视图
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): movieViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_movie_1_1, parent, false)
            //点击事件  获取点击的  list 中的数据
            val viewHolder = movieViewHolder(view)
            viewHolder.movie_Src.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = moveinfo_1[position]
                Toast.makeText(parent.context,"${info.movieName_1}", Toast.LENGTH_LONG).show()
                val mIntent = Intent(context, MovieDetailsActivity::class.java)
                mIntent.putExtra("movie_name", info.movieName_1)//可能要改进
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                context.startActivity(mIntent)
            }
            viewHolder.move_goupiao.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = moveinfo_1[position]
                Toast.makeText(parent.context,"${info.movieNameScoreDate_1}", Toast.LENGTH_LONG).show()
                val mIntent = Intent(context, SelectCinemaActivity::class.java)
                mIntent.putExtra("movie_name", info.movieName_1)//可能要改进
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                context.startActivity(mIntent)

            }
            return viewHolder
        }
        //绑定数据
        override fun onBindViewHolder(holder: movieViewHolder, position: Int) {
            val info = moveinfo_1[position]
            holder.move_Name.text = info.movieName_1
            holder.move_ScoreDate.text = info.movieNameScoreDate_1
            holder.movie_Src.setImageResource(info.movieSrc_1)
            holder.move_goupiao.setImageResource(info.moviegoupiap_1)
        }
        //获取列表行数
        override fun getItemCount(): Int {
            return moveinfo_1.size
        }
    }
    //2-----
    private class movieViewHolder1(view: View) : RecyclerView.ViewHolder(view) {
        var move_Name_2: TextView = view.findViewById(R.id.moveName_2)
        var movie_Src_2: com.makeramen.roundedimageview.RoundedImageView = view.findViewById(R.id.movieSrc_2)
        var move_ScoreDate_2: TextView = view.findViewById(R.id.movieNameScoreDate_2)
        var move_goupiao_2: com.makeramen.roundedimageview.RoundedImageView = view.findViewById(R.id.goupiao_2)
    }
    //适配器
    private class MovieAapter1(val moveinfo_2: List<movie_1_2>, val context: Context): RecyclerView.Adapter<movieViewHolder1>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): movieViewHolder1 {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_movie_1_2, parent, false)
            //点击事件  获取点击的  list 中的数据
            val viewHolder = movieViewHolder1(view)
            viewHolder.movie_Src_2.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = moveinfo_2[position]
                Toast.makeText(parent.context,"${info.movieName_2}", Toast.LENGTH_LONG).show()
                val mIntent = Intent(context, MovieDetailsActivity::class.java)
                mIntent.putExtra("movie_name", info.movieName_2)//可能要改进
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                context.startActivity(mIntent)
            }
            viewHolder.move_goupiao_2.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = moveinfo_2[position]

                if (info.movie_wanted == "true"){
                    info.movie_wanted = "false"
                    viewHolder.move_goupiao_2.setImageResource(R.drawable.p4)
                    Toast.makeText(parent.context,"已取消想看", Toast.LENGTH_LONG).show()
                    getAllTrainInfoJson4(info.movieSrc_2)
                }
                else{
                    info.movie_wanted = "true"
                    viewHolder.move_goupiao_2.setImageResource(R.drawable.p6)
                    Toast.makeText(parent.context,"已加入想看", Toast.LENGTH_LONG).show()
                    getAllTrainInfoJson3(info.movieSrc_2)
                }
            }
            return viewHolder
        }
        //绑定数据
        override fun onBindViewHolder(holder: movieViewHolder1, position: Int) {
            val info = moveinfo_2[position]
            holder.move_Name_2.text = info.movieName_2
            holder.move_ScoreDate_2.text = info.movieNameScoreDate_2
            holder.movie_Src_2.setImageResource(info.movieSrc_2)
            //holder.move_goupiao_2.setImageResource(info.moviegoupiap_2)
            if (info.movie_wanted == "true"){
                holder.move_goupiao_2.setImageResource(R.drawable.p6)
            }
            else{
                holder.move_goupiao_2.setImageResource(R.drawable.p4)
            }
        }
        //获取列表行数
        override fun getItemCount(): Int {
            return moveinfo_2.size
        }

        private fun getAllTrainInfoJson3(wanted_movie_src:Int){
            val sever_ip = "192.168.43.8"
            val addWantedMoive = "http://${sever_ip}:8080/JspForAndroid/addWantedMovie.jsp"
            //val addWantedMoive = "http://${context.getString(R.string.sever_ip)}:8080/JspForAndroid/addWantedMovie.jsp"
            thread {
                try {
                    val client = OkHttpClient()
                    val movie_src = wanted_movie_src.toString()

                    val requestBody = FormBody.Builder()
                        .add("wanted_movie_src", URLEncoder.encode(movie_src,"UTF-8"))
                        .build()

                    //构建请求
                    val request = Request.Builder()
                        .url(addWantedMoive)
                        .post(requestBody)
                        .build()
                    //执行
                    client.newCall(request).execute()
                    //得到返回值

                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
        }
        private fun getAllTrainInfoJson4(wanted_movie_src:Int){
            val sever_ip = "192.168.43.8"
            val deleteWantedMoive = "http://${sever_ip}:8080/JspForAndroid/deleteWantedMovie.jsp"
            //val deleteWantedMoive = "http://${context.getString(R.string.sever_ip)}:8080/JspForAndroid/deleteWantedMovie.jsp"
            thread {
                try {
                    val client = OkHttpClient()
                    val movie_src = wanted_movie_src.toString()

                    val requestBody = FormBody.Builder()
                        .add("wanted_movie_src", URLEncoder.encode(movie_src,"UTF-8"))
                        .build()

                    //构建请求
                    val request = Request.Builder()
                        .url(deleteWantedMoive)
                        .post(requestBody)
                        .build()
                    //执行
                    client.newCall(request).execute()
                    //得到返回值

                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
        }
    }
//----------------------------------------------------------------------------------------------
    //数据传输
    //json解析
    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                //构建请求
                val request = Request.Builder()
                    .url(showAll_Home_Movie_1_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
                //txtData.text = responseData
                val result = parseJson(responseData)
                if (responseData != null){
                    activity?.runOnUiThread{
                        //修改布局
                        //txtData.text = result

                        var layoutManager = LinearLayoutManager( context)
                        layoutManager.orientation = LinearLayoutManager.HORIZONTAL
                        myrecyclerview.layoutManager = layoutManager
                        var adapter = MovieAapter(moveinfo_1,this.requireContext())
                        myrecyclerview.adapter = adapter
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson(jsonData:String?):String{
        val builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            moveinfo_1.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val movie_name = jsonObject.getString("movie_name")
                val movie_src = jsonObject.getString("movie_src")
                val movie_score = jsonObject.getString("movie_score")
                val movie_kind = jsonObject.getString("movie_kind")

                builder.append("$movie_name--$movie_src--$movie_score--$movie_kind, ")
                moveinfo_1.add(movie_1_1(movie_name, getResourceIdByString(movie_src),
                    movie_score, getResourceIdByString(movie_kind)))
            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getAllTrainInfoJson2(){
        thread {
            try {
                val client = OkHttpClient()

                //构建请求
                val request = Request.Builder()
                    .url(showAll_Home_Movie_2_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
                //txtData.text = responseData
                val result = parseJson2(responseData)
                if (responseData != null){
                    activity?.runOnUiThread{
                        //修改布局
                        //txtData.text = result

                        var layoutManager1 = LinearLayoutManager( context)
                        layoutManager1.orientation = LinearLayoutManager.HORIZONTAL
                        myrecyclerview1.layoutManager = layoutManager1
                        var adapter2 = MovieAapter1(moveinfo_2, this.requireContext())
                        myrecyclerview1.adapter = adapter2
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson2(jsonData:String?):String{
        val builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            moveinfo_2.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val movie_name = jsonObject.getString("movie_name")
                val movie_src = jsonObject.getString("movie_src")
                val movie_date = jsonObject.getString("movie_date")
                val movie_kind = jsonObject.getString("movie_kind")
                val movie_wanted = jsonObject.getString("movie_wanted")

                builder.append("$movie_name--$movie_src--$movie_date--$movie_kind, ")
                moveinfo_2.add(movie_1_2(movie_name, getResourceIdByString(movie_src),
                    movie_date, getResourceIdByString(movie_kind), movie_wanted))
            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
}
